<?php
/**
 * logs.inc.php
 */

if(!defined('IN_SITE') || !defined('IN_ADMIN')) {
	exit('Access Denied');
}

$logdir = SITE_ROOT.'data/log/';
$logfiles = get_log_files($logdir, 'cplog');
$logs = array();
rsort($logfiles);
if($logfiles) {
	$logs = file(!empty($day) ? $logdir.$day.'_cplog.php' : $logdir.$logfiles[0]);
}
$pagesize = intval($pagesize) ? $pagesize : 30;
$page = max(1, intval($page));
$start = ($page - 1) * $pagesize;
$logs = array_reverse($logs);

if(empty($keyword)) {
	$num = count($logs);
	$multipage = multi($num, $pagesize, $page, "admincp.php?action=logs&pagesize=$pagesize".(!empty($day) ? '&day='.$day : ''), 0, 3);
	$logs = array_slice($logs, $start, $pagesize);

} else {
	foreach($logs as $key => $value) {
		if(strpos($value, $keyword) === FALSE) {
			unset($logs[$key]);
		}
	}
	$multipage = '';
}
$showtable = $tableclass = '';
foreach($logs as $k => $logrow) {
	if($k%2 == 0) {$tableclass = ' class="trbgcolor";';} else {$tableclass = '';}
	$showtable .= "<tr$tableclass>";
	$log = explode("\t", $logrow);
	if(empty($log[1])) {
		continue;
	}
	$log[1] = gmdate('y-n-j H:i', $log[1]+8*3600);
	$log[6] = cutstr($log[6], 280);
	$showtable .= '<td class="smalltxt" style="text-align: center;">'.$log[2].'</td><td class="smalltxt" style="text-align: center;">'.$log[4].'</td><td class="smalltxt" style="text-align: center;">'.$log[1].'</td><td class="smalltxt" style="text-align: center;">'.$log[5].'</td><td class="smalltxt">'.$log[6].'</td></tr>';
}

if($logfiles) {
	$sel = '<select onchange="location.href=\'admincp.php?action=logs&day=\'+this.value">';
	foreach($logfiles as $logfile) {
		list($date) = explode('_', $logfile);
		$sel .= '<option value="'.$date.'"'.($date == $day ? ' selected="selected"' : '').'>'.$date.'</option>';
	}
	$sel .= '</select>';
} else {
	$sel = '';
}
include admin_tpl("logs");

function get_log_files($logdir = '', $action = 'action') {
	$dir = opendir($logdir);
	$files = array();
	while($entry = readdir($dir)) {
		$files[] = $entry;
	}
	closedir($dir);

	if($files) {
		sort($files);
		$logfile = $action;
		$logfiles = array();
		$ym = '';
		foreach($files as $file) {
			if(strpos($file, $logfile) !== FALSE) {
				if(substr($file, 0, 6) != $ym) {
					$ym = substr($file, 0, 6);
				}
				$logfiles[$ym][] = $file;
			}
		}
		if($logfiles) {
			$lfs = array();
			foreach($logfiles as $ym => $lf) {
				$lastlogfile = $lf[0];
				unset($lf[0]);
				$lf[] = $lastlogfile;
				$lfs = array_merge($lfs, $lf);
			}
			return array_slice($lfs, -2, 2);
		}
		return array();
	}
	return array();
}
?>